package com.gin.kotlin.gf2gamecommunity.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.gin.kotlin.enums.MessageType
import com.gin.kotlin.form.MessageReadForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.livedata.CachedLiveData
import com.gin.kotlin.gf2gamecommunity.base.livedata.CachedPagingData
import com.gin.kotlin.gf2gamecommunity.callback.AbstractNothingCallback
import com.gin.kotlin.gf2gamecommunity.pagingsource.MessageListPagingData
import com.gin.kotlin.response.Res
import com.gin.kotlin.response.message.Message
import com.gin.kotlin.response.message.UnreadCount
import kotlinx.coroutines.delay
import retrofit2.await

/**
 * 提醒消息ViewModel
 * @property unreadCount 未读消息数
 * @property messageList 消息列表
 * @constructor
 */
class MessageViewModel : ViewModel() {
    init {
        Log.i(TAG, "实例化")
    }

    val unreadCount = CachedLiveData<Res<UnreadCount>, UnreadCount>(
        requestMethod = { api().getUnreadCount() },
        bodyTransform = { it.data },
    )

    val messageList = CachedPagingData<Message, MessageType>(scope = viewModelScope) { MessageListPagingData(it) }

    /**
     * 将消息设置为已读
     * @param id Int
     * @param type MessageType
     */
    fun read(id: Int, type: MessageType) = api().read(MessageReadForm(id, type)).enqueue(object : AbstractNothingCallback() {
        override fun onSuccess(message: String) {
            unreadCount.fetch(true)
            Log.i(TAG, "消息已读: $message, id: $id")
        }
    })

    /**
     * 全部已读
     * @param type MessageType
     * @param ids List<Int>
     */
    suspend fun readAll(type: MessageType, ids: List<Int>) {
        ids.forEach { id ->
            val message = api().read(MessageReadForm(id, type)).await().message
            Log.i(TAG, "消息已读: $message, id: $id")
            delay(100)
        }
        unreadCount.fetch(true)
    }


    private fun api() = App.INSTANCE.api.messageApi

    companion object {
        private val TAG = MessageViewModel::class.java.simpleName

    }
}